//
//  RetrievePasswordVC.m
//  CoolTennisBall
//
//  Created by Coollang on 16/10/25.
//  Copyright © 2016年 CoolLang. All rights reserved.
//

#import "RetrievePasswordVC.h"
#import "LoginService.h"

@interface RetrievePasswordVC ()

@property (weak, nonatomic) IBOutlet UITextField *emailTextField;

@property (weak, nonatomic) IBOutlet UIView *finishSuperView;

@property (weak, nonatomic) IBOutlet UILabel *messageLabelOne;

@property (weak, nonatomic) IBOutlet UILabel *messageLabelTwo;

@property (weak, nonatomic) IBOutlet UIButton *tryAnginButton;

@property (strong, nonatomic) LoginService *logService;

@property (weak, nonatomic) IBOutlet UILabel *pleaseEmailAddressLab;

@property (weak, nonatomic) IBOutlet UIButton *continueButton;

@property (weak, nonatomic) IBOutlet UIButton *finishButton;

@end

@implementation RetrievePasswordVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.finishSuperView.hidden = YES;
    
    [self configureLocalization];
}

- (void)configureLocalization {
    self.title = NSLocalizedString(@"Retrieve Passsword", nil);
    self.pleaseEmailAddressLab.text = NSLocalizedString(@"Please enter your e-mail address:", nil);
    [self.continueButton setTitle:NSLocalizedString(@"Continue", nil) forState:UIControlStateNormal];
    [self.finishButton setTitle:NSLocalizedString(@"Finish", nil) forState:UIControlStateNormal];
}

- (void)setMessageLabelTextWithUserEmail:(NSString *)email {
  
    NSString *messageStrOne = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"An e-mail has been sent to:\n", nil),email];
   
    self.messageLabelOne.attributedText = [NSAttributedString attributedString:messageStrOne subString:@[NSLocalizedString(@"An e-mail has been sent to:\n", nil),email] colors:@[kHasReadColor,kOrangeColor] fonts:@[[UIFont systemFontOfSize:20],[UIFont systemFontOfSize:20]]];
    
    self.messageLabelTwo.text = NSLocalizedString(@"Please check your inbox for a\nmessage form Coollang and follow\nthe insrtuctions in the message.", nil) ;
    
    NSString *messageStrThree = [NSString stringWithFormat:NSLocalizedString(@"If you do not receive the e-mail,\nplease check your spam folder or\n%@ later.", nil),NSLocalizedString(@"try again", nil)];
    
    NSMutableAttributedString *attrStrM = [[NSMutableAttributedString alloc] initWithString:messageStrThree];
    
    [attrStrM addAttributes:@{NSForegroundColorAttributeName:kOrangeColor,NSUnderlineColorAttributeName:kOrangeColor,NSUnderlineStyleAttributeName:@(1)} range:[messageStrThree rangeOfString:NSLocalizedString(@"try again", nil)]];
    self.tryAnginButton.titleLabel.numberOfLines = 0;
    [self.tryAnginButton setTitleColor:kSelectedColor forState:UIControlStateNormal];
    [self.tryAnginButton setAttributedTitle:attrStrM.copy forState:UIControlStateNormal];
    
}

- (IBAction)tryAnainButtonClick:(id)sender {
    [self continueBtnClick:nil];
}

- (IBAction)continueBtnClick:(id)sender {
    
    [self.emailTextField resignFirstResponder];
    
    if (![self verifyEmail]) {
        FUIAlertView *alertView = [self.logService AlertViewWithTitle:nil message:@"Please enter a valid email address" cancelButtonTitle:@"OK"];
        [alertView show];
        return;
    }
    
    YFLoginApi *retrieveApi = [YFLoginApi forgotpasswordWithEmail:self.emailTextField.text];
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [[YFNetworkingService sharedInstance] sendRequest:retrieveApi callback:^(BOOL success, id result, NSError *error) {
        NSString *retString = retrieveApi.responseJSONObject[@"ret"];
        NSLog(@"%@--%@",retString,retrieveApi.responseJSONObject);
        if (success) {
            if ([retString isEqualToString:@"0"]) {
                if (self.finishSuperView.hidden ==  YES) {
                    self.finishSuperView.hidden = NO;
                    [self setMessageLabelTextWithUserEmail:self.emailTextField.text];
                }else {
                    FUIAlertView *alertView = [self.logService AlertViewWithTitle:nil message:@"An new email has been sent successfully！" cancelButtonTitle:@"OK"];
                    [alertView show];
                }
            }
        }else {
            if ([retString isEqualToString:@"-10016"]) {
                // 一分钟智能发送一封邮件
                FUIAlertView *alertView = [self.logService AlertViewWithTitle:nil message:@"One minute can only send an E-mail" cancelButtonTitle:@"OK"];
                [alertView show];
                
            }else if ([retString isEqualToString:@"-10002"]) {
                // 用户不存在
                FUIAlertView *alertView = [self.logService AlertViewWithTitle:nil message:@"User does not exist" cancelButtonTitle:@"OK"];
                [alertView show];
            }
        }
        
    }];
    
}

- (IBAction)backClick:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)finishBtnClick:(UIButton *)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"FindPasswordCompleted" object:self.emailTextField.text];
}
- (BOOL)verifyEmail{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailVerify = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailVerify evaluateWithObject:self.emailTextField.text];
}

- (LoginService *)logService{
    if (!_logService) {
        self.logService = [[LoginService alloc] init];
    }
    return _logService;
}

@end
